/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package presentacion;

import java.util.ArrayList;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import logica.ControladorArticulos;
import logica.ControladorCaracteristicas;

/**
 *
 * @author Andres
 */
public class MoverStock extends AZPanel {

    private ControladorCaracteristicas caracteristicas;
    private ControladorArticulos articulos;
    
    @Override
    protected void cargarCaracteristicas() {
        agregarCombosALineasFactura(this.jTable3);        
        cargarCombo("locales", this.jComboBox1);
        cargarCombo("locales", this.jComboBox2);
    }

    public ControladorArticulos getArticulos() {
        return articulos;
    }

    public void setArticulos(ControladorArticulos articulos) {
        this.articulos = articulos;
    }
    
    /**
     * Creates new form MoverStock
     */
    public MoverStock() {
        initComponents();
    }
    
    private void agregarCombosALineasFactura(JTable a) {
        JComboBox combo = new JComboBox();
        cargarCombo("descripciones", combo);
        TableColumn col = a.getColumnModel().getColumn(0);
        col.setCellEditor(new DefaultCellEditor(combo));

        combo = new JComboBox();
        cargarCombo("talles", combo);
        col = a.getColumnModel().getColumn(1);
        col.setCellEditor(new DefaultCellEditor(combo));

        combo = new JComboBox();
        cargarCombo("colores", combo);
        col = a.getColumnModel().getColumn(2);
        col.setCellEditor(new DefaultCellEditor(combo));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();
        jButton3 = new javax.swing.JButton();
        jScrollPane7 = new javax.swing.JScrollPane();
        jTable3 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setMinimumSize(new java.awt.Dimension(975, 528));

        jLabel2.setText("De:");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel3.setText("a:");

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jButton3.setText("Agregar linea");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jTable3.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"", "", "",  new Integer(0)},
                {"", "", "",  new Integer(0)},
                {"", "", "",  new Integer(0)},
                {"", "", "",  new Integer(0)}
            },
            new String [] {
                "Producto", "Talle", "Color", "Cantidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane7.setViewportView(jTable3);

        jButton1.setText("Mover stock");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton6.setText("Borrar lineas");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 256, Short.MAX_VALUE)
                        .addComponent(jButton3))
                    .addComponent(jScrollPane7)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)))
                .addContainerGap(260, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jButton6)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(49, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        DefaultTableModel a = (DefaultTableModel) this.jTable3.getModel();
        a.addRow(new Object[]{"", "", "", new Integer(0)});
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.jLabel1.setText("");
        String de = this.jComboBox1.getSelectedItem().toString();
        if(de.equals("")){
            this.jLabel1.setText("Ingrese De");
            return;
        }
        String a = this.jComboBox2.getSelectedItem().toString();
        if(a.equals("")){
            this.jLabel1.setText("Ingrese A");
            return;
        }
        
        TableModel tabla = this.jTable3.getModel();
        ArrayList<String[]> lineas = new ArrayList<String[]>();
        String p, t, c, cant;
        for (int i = 0; i < tabla.getRowCount(); i++) {
            p = tabla.getValueAt(i, 0).toString();
            t = tabla.getValueAt(i, 1).toString();
            c = tabla.getValueAt(i, 2).toString();
            if(tabla.getValueAt(i, 3) != null){
                cant = tabla.getValueAt(i, 3).toString();
            } else {
                cant = "0";
            }
            if (!p.equals("") && !t.equals("") && !c.equals("") && !cant.equals("0")) {
                lineas.add(new String[]{p, t, c, cant});
            } else {
                if (!(p.equals("") && t.equals("") && c.equals("") && cant.equals("0"))) {
                    this.jLabel1.setText("La linea " + (i + 1) + " tiene campos en blanco.");
                    return;
                }
            }
        }
        boolean resultado_de = false;
        boolean resultado_a = false;
        int i;
        for (i = 0; i < lineas.size(); i++) {
            p = lineas.get(i)[0];
            t = lineas.get(i)[1];
            c = lineas.get(i)[2];
            cant = lineas.get(i)[3];
            resultado_de = this.articulos.actualizarStock(p, t, c, de, -Integer.parseInt(cant));
            if (!resultado_de) {
                break;
            }
            resultado_a = this.articulos.actualizarStock(p, t, c, a, Integer.parseInt(cant));
            if (!resultado_a) {
                break;
            }
        }
        if (i != lineas.size()) {
            // Si ocurrió un error revierto los cambios
            for (int j = 0; j < i; j++) {
                p = lineas.get(j)[0];
                t = lineas.get(j)[1];
                c = lineas.get(j)[2];
                cant = lineas.get(j)[3];
                this.articulos.actualizarStock(p, t, c, de, Integer.parseInt(cant));
                this.articulos.actualizarStock(p, t, c, a, -Integer.parseInt(cant));
            }
            // Revierto la ultima transaccion considerando que haya fallado en la mitad
            p = lineas.get(i)[0];
            t = lineas.get(i)[1];
            c = lineas.get(i)[2];
            cant = lineas.get(i)[3];
            if (!resultado_de) {
                this.articulos.actualizarStock(p, t, c, de, Integer.parseInt(cant));
            }
            if (!resultado_a) {
                this.articulos.actualizarStock(p, t, c, a, -Integer.parseInt(cant));
            }
            //ControladorEtiquetas.limpiar(archivo);
            this.jLabel1.setText("Ocurrio un error.");
            return;
        }
        this.jLabel1.setText("Opercación exitosa");
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        jTable3.setModel(new javax.swing.table.DefaultTableModel(
            new Object[][]{
                {"", "", "", new Integer(0)},
                {"", "", "", new Integer(0)},
                {"", "", "", new Integer(0)},
                {"", "", "", new Integer(0)}
            },
            new String[]{
                "Producto", "Talle", "Color", "Cantidad"
            }) {
                Class[] types = new Class[]{
                    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
                };

                public Class getColumnClass(int columnIndex) {
                    return types[columnIndex];
                }
            });
            agregarCombosALineasFactura(this.jTable3);
            this.jLabel1.setText("");
    }//GEN-LAST:event_jButton6ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton6;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JTable jTable3;
    // End of variables declaration//GEN-END:variables
}
